package main

import "fmt"

type ListNode struct {
	Next *ListNode
	Val  int
}

func ListNodeInit(Val int) *ListNode {
	return &ListNode{
		Next: nil,
		Val:  Val,
	}
}

func (l *ListNode) print() {
	var index = 1
	for {
		if l.Next == nil {
			fmt.Printf("index: %d, Value: %d\n", index, l.Val)
			break
		}
		fmt.Printf("index: %d, Value: %d\n", index, l.Val)
		index++
		l = l.Next
	}
}

func (l *ListNode) insert(Val int) bool {
	for {
		if l.Next == nil {
			break
		}
		l = l.Next
	}

	l.Next = &ListNode{
		Next: nil,
		Val:  Val,
	}

	return true
}

// 第一次想法比较直接
func mergeTwoList(l1, l2 *ListNode) *ListNode {
	rl := &ListNode{}
	head := rl

	for {
		if l1 == nil && l2 == nil {
			break
		}
		if l1 == nil {
			head.Next = l2
			l2 = l2.Next
			head = head.Next
			continue
		}
		if l2 == nil {
			head.Next = l1
			l1 = l1.Next
			head = head.Next
			continue
		}
		if l1.Val < l2.Val {
			head.Next = l1
			l1 = l1.Next
		} else {
			head.Next = l2
			l2 = l2.Next
		}
		head = head.Next
	}

	return rl.Next
}

func mergeTwoListBetter(l1, l2 *ListNode) *ListNode {
	head := &ListNode{}
	cur := head
	for l1 != nil && l2 != nil {
		if l1.Val < l2.Val {
			cur.Next = l1
			l1 = l1.Next
		} else {
			cur.Next = l2
			l2 = l2.Next
		}
		cur = cur.Next
	}
	if l1 == nil {
		cur.Next = l2
	}
	if l2 == nil {
		cur.Next = l1
	}
	return head.Next
}
